package com.demo.seckill.mybatis;

import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author libo
 * @ClassName UserMapper
 * @date 2018/12/28 16:25
 */
@Mapper
public interface UserMapper {
    @Select("select * from userinfo")
    List<UserInfo> list();

    @SelectProvider(type = UserSqlProvider.class,method = "listByName")
    @ResultMap("com.demo.seckill.mybatis.UserMapper.userInfoMap")
    List<UserInfo> listByName(String name);

    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "username"),
            @Result(property = "age", column = "age"),
            @Result(property = "sex", column = "sex"),
            @Result(property = "addressId", column = "address_id")
    })
    @Select("select * from userinfo")
    List<UserInfo> listSample();

    /*@ResultMap("com.demo.seckill.mybatis.UserMapper.userInfoMap")
    @Select("select * from userinfo where username like #{name} and sex like #{sex}")*/
    UserInfo get(@Param("name") String name, @Param("sex") String sex);

    @SelectProvider(type = UserSqlProvider.class, method = "getBadUser")
    List<UserInfo>  getBadUser(@Param("name") String name, @Param("sex") String sex);

    @Insert("insert into userinfo(username,age,sex) values (#{name},#{age},#{sex})")
    int insertUserInfo(@Param("name") String name,@Param("age")int age, @Param("sex") String sex);

    @Insert("insert into userinfo(username,age,sex) values (#{userInfo.name},#{userInfo.age},#{userInfo.sex})")
    int insertUserInfo2(@Param("userInfo") UserInfo userInfo);

    @Update("update userinfo set username = #{name} where id =#{id}")
    int updateUserInfo(@Param("name") String name,@Param("id") int id);

    @Delete("delete from  userinfo where username =#{name}")
    int deleteUserInfo(@Param("name") String name);

    @Delete("delete from  userinfo where username =#{userInfo.name}")
    int deleteUserInfo2(@Param("userInfo") UserInfo userInfo);

    @Select("SELECT * FROM `userinfo` WHERE id = #{id}")
    @Results({
            @Result(property = "name", column = "username"),
            @Result(property = "addressId",column = "address_id"),
            @Result(property = "address", column = "address_id",
                    one  = @One(select = "com.demo.seckill.mybatis.AddressMapper.findAddressById"))
    })
    UserInfo getUserWithAddress(@Param("id")int id);

    @Select("SELECT * FROM `userinfo` WHERE id = #{id}")
    @Results({
            @Result(property = "name", column = "username"),
            @Result(property = "addressId",column = "address_id"),
            @Result(property = "cars", column = "id",
                    many = @Many(select = "com.demo.seckill.mybatis.CarMapper.findCarByUserId")),
            @Result(property = "address", column = "address_id",
                    one  = @One(select = "com.demo.seckill.mybatis.AddressMapper.findAddressById"))
    })
    UserInfo getUserWithCar(@Param("id") int id);
}
